package info.openlvb.openface.client.handler;

import info.openlvb.openface.client.base.Account;
import info.openlvb.openface.client.base.person.AddPersonPanel;
import info.openlvb.openface.client.service.LdapService;
import info.openlvb.openface.client.service.LdapServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;

public class AddPersonListener extends ButtonListenerAdapter{

	AddPersonPanel addPersonPanel;
	private final LdapServiceAsync ldapService = GWT.create(LdapService.class);

	public AddPersonListener(AddPersonPanel addPersonPanel) {
		this.addPersonPanel = addPersonPanel;
	}

	public void onClick(Button button, EventObject e) {
		if(addPersonPanel.getPassword().getText().equals(addPersonPanel.getConfirmpassword().getText())){
			final Account account = new Account();
			//description = gecos
			account.setDescription(addPersonPanel.getDescription());
			//login
			account.setLogin(addPersonPanel.getLogin().getText());
			//nom
			account.setNom(addPersonPanel.getNom().getText());
			//nom complet = sn
			account.setNom_complet(addPersonPanel.getNom().getText());
			//prenom
			account.setPrenom(addPersonPanel.getPrenom().getText());
			//mail
			account.setMail(addPersonPanel.getMail().getText());
			//others
			account.setShell("/dev/null");
			account.setSambaEnabled(addPersonPanel.getChkrepperso().isEnabled());
			account.setPassword(addPersonPanel.getPassword().getText());

			// test si utilisateur existe
			ldapService.searchAccountByUid(account.getLogin(), new AsyncCallback<Account>() {
				public void onFailure(Throwable caught) {
					MessageBox.alert("problème de backend");
				}
				public void onSuccess(Account result) {
					if(result!=null){
						MessageBox.alert("le compte existe déjà ...");
					}else{
						ldapService.addUser(account, new AsyncCallback<Void>() {
							public void onSuccess(Void result) {
								MessageBox.alert("Utilisateur ajouté");
								addPersonPanel.getChkmail().setValue(false);
								addPersonPanel.getChkrepperso().setValue(false);
								addPersonPanel.getConfirmpassword().setValue("");
								//addPersonPanel.getDescription().setValue("");
								addPersonPanel.getLogin().setValue("");
								addPersonPanel.getMail().setValue("");
								addPersonPanel.getNom().setValue("");
								addPersonPanel.getPassword().setValue("");
								addPersonPanel.getPrenom().setValue("");
								addPersonPanel.getRepPerso().setValue("");

							}
							public void onFailure(Throwable caught) {
								MessageBox.alert("problème de backend");
							}
						});
					}
				}
			});
		}
	}


}
